package com.cuit.springboot.util;

import java.io.IOException;

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializerProvider;

@Configuration
public class JacksonConfig {
	
	/**
	 * 解决null值转空字符串
	 * @param builder
	 * @return
	 */
	@Bean
	@Primary
	@ConditionalOnMissingBean(ObjectMapper.class)
	public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
		ObjectMapper objectMapper = builder.createXmlMapper(false).build();
		SerializerProvider serializerProvider = objectMapper
				.getSerializerProvider();
		serializerProvider.setNullValueSerializer(new JsonSerializer<Object>() {
			@Override
			public void serialize(Object o, JsonGenerator jsonGenerator,
					SerializerProvider serializerProvider) throws IOException,
					JsonProcessingException {
				jsonGenerator.writeString(" ");
			}
		});
		return objectMapper;
	}
	
	@Bean
    public Jackson2ObjectMapperBuilderCustomizer customJackson() {
        return new Jackson2ObjectMapperBuilderCustomizer() {
            @Override
            public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {       
            	jacksonObjectMapperBuilder.serializationInclusion(Include.NON_NULL);      
            	jacksonObjectMapperBuilder.failOnUnknownProperties(false);         
            	jacksonObjectMapperBuilder.propertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);       
            	jacksonObjectMapperBuilder.configure(jacksonObjectMapper(jacksonObjectMapperBuilder));
            }
            
        };
    }


	
}
